import { message } from "antd";
import { getLocale } from 'umi'

const lang = getLocale()

/**
 * copy the string to clipboard
 * @param {string} text 
 */
const copyText = (text) => {
    navigator.clipboard.writeText(text)
    message.success(lang === 'en-US' ? 'Copied' : '复制成功')
}


/**
 * save the text to a json file
 * @param {string} text 
 */
const saveJsonFile = (text) => {
    try {
        const blob = new Blob([text], { type: 'application/json' })
        const link = document.createElement('a')
        link.href = window.URL.createObjectURL(blob)
        link.download = 'config.json'
        link.click()
        message.success(lang === 'en-US' ? 'Downloaded successfully' : '下载成功')
    } catch (e) {
        message.error(lang === 'en-US' ? 'Download failed, please check Json format' : '下载失败，请检查 Json 格式')
    }
}

/**
 * replace a string with a template
 * @param {string} template 
 * @param {any[]} Vars 
 * @returns 
 */
const templateReplace = (template, Vars = []) => {
    Vars.forEach(item => {
        template = template.replace(new RegExp("\\${.*" + item.name + ".*\\}", "g"), item.value);
    });
    return template;
};

export { copyText, saveJsonFile, templateReplace }
